<?php
/**
 * Mecache queue object
 * @author thonn
 *
 */
class SGN_MemcacheQ
{
    /**
     * Queue Config Object
     */
    private $_config = null;
    private static $_instance;
    private static $_host;
    private static $_port;
    private static $_queueName;
    
    /**
     * Constructor
     * 
     * @param String $host
     * @param Integer $port
     * @param String $queueName
     * 
     * @return Void
     */
    public function __construct ($host, $port, $queueName)
    {
        self::$_host = $host;
        self::$_port = $port;
        self::$_queueName = $queueName;
    }
    
	/**
	 * Create a single instance for this class
	 * @return SGN_MemcacheQ
	 * */
	public static function factory($host, $port, $queueName) 
	{
		if(!self::$_instance) {
			self::$_instance = new SGN_MemcacheQ($host, $port, $queueName);
		}

		return self::$_instance;
	}
    /**
     * Get queue value
     * 
     * @param Boolean $isUnserialize
     * 
     * @return Array
     */
    public function get ($length, $isUnserialize = true)
    {
        if (!intval($length)) {
            return;
        }
        $memcache_obj = memcache_connect(self::$_host, self::$_port);
        $contents = array();
        $gettedMessages = 0;
        do {
            $content = memcache_get($memcache_obj, self::$_queueName);
            if ($content) {
                if ($isUnserialize) {
                    $contents[] = unserialize($content);
                } else {
                    $contents[] = $content;
                }
            }
            $gettedMessages ++;
        } while ($gettedMessages < $length && $content);
        memcache_close($memcache_obj);
        return $contents;
    }
    /**
     * Set queue value
     * 
     * @param Array $value
     * @param Boolean $isSerialize
     * 
     * @return Void
     */
    public function set ($value, $isSerialize = true)
    {
        $memcache_obj = memcache_connect(self::$_host, self::$_port);
        if ($isSerialize) {
            $value = serialize($value);
        }
        memcache_set($memcache_obj, self::$_queueName, $value, 0, 0);
        memcache_close($memcache_obj);
    }
}